$(function () {

    // Preload images
    $.preloadCssImages();


    // CSS tweaks
    $('#header #nav li:last').addClass('nobg');
    $('.block_head ul').each(function () {
        $('li:first', this).addClass('nobg');
    });
    $('.block form input[type=file]').addClass('file');


    // Web stats
    $('table.stats').each(function () {

        if ($(this).attr('rel')) {
            var statsType = $(this).attr('rel');
        } else {
            var statsType = 'area';
        }

        var chart_width = ($(this).parent('div').width()) - 60;


        if (statsType == 'line' || statsType == 'pie') {
            $(this).hide().visualize({
                type:statsType, // 'bar', 'area', 'pie', 'line'
                width:chart_width,
                height:'240px',
                colors:['#6fb9e8', '#ec8526', '#9dc453', '#ddd74c'],

                lineDots:'double',
                interaction:true,
                multiHover:5,
                tooltip:true,
                tooltiphtml:function (data) {
                    var html = '';
                    for (var i = 0; i < data.point.length; i++) {
                        html += '<p class="chart_tooltip"><strong>' + data.point[i].value + '</strong> ' + data.point[i].yLabels[0] + '</p>';
                    }
                    return html;
                }
            });
        } else {
            $(this).hide().visualize({
                type:statsType, // 'bar', 'area', 'pie', 'line'
                width:chart_width,
                height:'240px',
                colors:['#6fb9e8', '#ec8526', '#9dc453', '#ddd74c']
            });
        }
    });


// Sort table
    $("table.sortable").tablesorter({
        headers:{ 0:{ sorter:false}, 5:{sorter:false} }, // Disabled on the 1st and 6th columns
        widgets:['zebra']
    });

    $('.block table tr th.header').css('cursor', 'pointer');


// Check / uncheck all checkboxes
    $('.check_all').click(function () {
        $(this).parents('form').find('input:checkbox').attr('checked', $(this).is(':checked'));
    });


// Set WYSIWYG editor
    $('.wysiwyg').wysiwyg({css:"css/wysiwyg.css", brIE:false });


// Modal boxes - to all links with rel="facebox"
    $('a[rel*=facebox]').facebox()

// Chosen
    if ($.fn.chosen) {
        $(".chzn-select").chosen();
        $(".chzn-select-deselect").chosen({allow_single_deselect:true});


        $("#uf_groupID").chosen().bind("change", function () {
            $("#userForm").validate().element($(this))
        });
        $("#lf_planID, #lf_locationID").chosen().bind("change", function () {
            $("#landForm").validate().element($(this))
        });
        $("#bf_buildingTypeID").chosen().bind("change", function () {
            $("#buildingForm").validate().element($(this))
        });
    }

// Validation
    if ($.fn.validate) {
        $(".validate-form").validate();

        $("#userForm").validate({
            ignore:".ignore",
            rules:{
                groupID:{
                    required:true
                }
            }
        });

        $("#landForm").validate({
            ignore:".ignore",
            rules:{
                locationID:{
                    required:true
                },
                planID:{
                    required:true
                }
            }
        });

        $("#buildingForm").validate({
            ignore:".ignore",
            rules:{
                buildingTypeID:{
                    required:true
                }
            }
        });
    }

// Chart Mode
    $('.chart_mode_wrapper .table_mode').click(function () {
        $(this).parents('.block_content').find('.stats').show();
        $(this).parents('.block_content').find('.visualize').hide();
        $(this).removeClass('gray').next().addClass('gray');
    });
    $('.chart_mode_wrapper .chart_mode').click(function () {
        $(this).parents('.block_content').find('.stats').hide();
        $(this).parents('.block_content').find('.visualize').show();
        $(this).removeClass('gray').prev().addClass('gray');
    });

    $('.chart_year').change(function () {
        $('.chart_form').submit();
    });

// Messages
    $('.block .message').hide().append('<span class="close" title="Dismiss"></span>').fadeIn('slow');
    $('.block .message .close').hover(
        function () {
            $(this).addClass('hover');
        },
        function () {
            $(this).removeClass('hover');
        }
    );

    $('.block .message .close').click(function () {
        $(this).parent().fadeOut('slow', function () {
            $(this).remove();
        });
    });

// Tabs
    $(".tab_content").hide();
    $("ul.tabs li:first-child").addClass("active").show();
    $(".block").find(".tab_content:first").show();

    $("ul.tabs li").click(function () {
        $(this).parent().find('li').removeClass("active");
        $(this).addClass("active");
        $(this).parents('.block').find(".tab_content").hide();

        var activeTab = $(this).find("a").attr("href");
        $(activeTab).show();

        // refresh visualize for IE
        $(activeTab).find('.visualize').trigger('visualizeRefresh');

        return false;
    });


// Sidebar Tabs
    $(".sidebar_content").hide();

    if (window.location.hash && window.location.hash.match('sb')) {

        $("ul.sidemenu li a[href=" + window.location.hash + "]").parent().addClass("active").show();
        $(".block .sidebar_content#" + window.location.hash).show();
    } else {

        $("ul.sidemenu li:first-child").addClass("active").show();
        $(".block .sidebar_content:first").show();
    }

    $("ul.sidemenu li").click(function () {

        var activeTab = $(this).find("a").attr("href");
        window.location.hash = activeTab;

        $(this).parent().find('li').removeClass("active");
        $(this).addClass("active");
        $(this).parents('.block').find(".sidebar_content").hide();
        $(activeTab).show();
        return false;
    });


// Block search
    $('.block .block_head form .text').bind('click', function () {
        $(this).attr('value', '');
    });


// Image actions menu
    $('ul.imglist li').hover(
        function () {
            $(this).find('ul').css('display', 'none').fadeIn('fast').css('display', 'block');
        },
        function () {
            $(this).find('ul').fadeOut(100);
        }
    );


// Image delete confirmation
    $('ul.imglist .delete a').click(function () {
        if (confirm("Are you sure you want to delete this image?")) {
            return true;
        } else {
            return false;
        }
    });


// Style file input
    $("input[type=file]").filestyle({
        image:"images/upload.gif",
        imageheight:30,
        imagewidth:80,
        width:250
    });


// File upload
    if ($('#fileupload').length) {
        new AjaxUpload('fileupload', {
            action:'upload-handler.php',
            autoSubmit:true,
            name:'userfile',
            responseType:'text/html',
            onSubmit:function (file, ext) {
                $('.fileupload #uploadmsg').addClass('loading').text('Uploading...');
                this.disable();
            },
            onComplete:function (file, response) {
                $('.fileupload #uploadmsg').removeClass('loading').text(response);
                this.enable();
            }
        });
    }


    $.extend(DateInput.DEFAULT_OPTS, {
        stringToDate:function (string) {
            var matches;
            if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
                return new Date(matches[1], matches[2] - 1, matches[3]);
            } else {
                return null;
            }
            ;
        },

        dateToString:function (date) {
            var month = (date.getMonth() + 1).toString();
            var dom = date.getDate().toString();
            if (month.length == 1) month = "0" + month;
            if (dom.length == 1) dom = "0" + dom;
            return date.getFullYear() + "-" + month + "-" + dom;
        }
    });

// Date picker
    $('input.date_picker').date_input();


// Navigation dropdown fix for IE6
    if (jQuery.browser.version.substr(0, 1) < 7) {
        $('#header #nav li').hover(
            function () {
                $(this).addClass('iehover');
            },
            function () {
                $(this).removeClass('iehover');
            }
        );
    }


// IE6 PNG fix
    $(document).pngFix();

// Disable parent menu
    $('#nav .has_childs').click(function () {
        return false;
    })

// Confirm delete
    $('.confirm-button').click(function () {
        if (confirm("You are about to delete this item. \nIt cannot be restored at a later time! Continue?")) {
            return true;
        } else {
            return false;
        }
    });

    $('.action_submit').click(function () {
        selectVal = $(".action_select").val();
        if (selectVal == '')
            return false;
        size = $('.action_form').find("input:checkbox:checked").size();

        if (size <= 0) {
            if (alert('Please select at least one item.'))
                return false;
            return false;
        }

        if (selectVal.indexOf("delete") >= 0) {
            if (confirm("You are about to delete these items. \nThem cannot be restored at a later time! Continue?")) {
                return true;
            } else {
                return false;
            }
        }

        return true;
    })

    $('.only-number').keypress(
        function (event) {
            var charCode = (event.which) ? event.which : event.keyCode
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;

            return true;
        });

    // select row
    $('.select-row').hover(
        function () {
            $(this).addClass("hover");
        },
        function () {
            $(this).removeClass("hover");
        }
    );
    $('.select-row').click(function(){
        parentForm = $(this).parents('form');
        parentForm.children('input[type=hidden]').val($(this).attr('title'));
        parentForm.submit();
    })

});